// graceUI/components/graceSwipeList.js
Component({
  properties: {
    width:{type:Number, value:750},
		msgs:{type:Array,value:[]},
		imgSize:{type:Array,value:['80rpx', '80rpx']},
		fontSizes:{type:Array,value:['28rpx','22rpx', '22rpx']},
		fontColors:{type:Array,value:['#323232','#888888', '#888888']},
		btnWidth:{type:Number, value:160}
  },
  data: {
    msgsIn: [],
		damping : 0.1
  },
  ready:function(){
    this.init(this.data.msgs);
    watch(this, {
      msgs: function (vn, vo) {
        this.init(vn);
      }
    });
  },
  methods: {
		init:function(msgs){
			var newmsg = [];
			msgs.forEach((item) => { item.x = 0; newmsg.push(item); });
			this.setData({msgsIn : newmsg});
		},
		thStart : function(e){
      var index = e.detail[1][0];
			this.setData({damping : 0.1});
      var i = 0;
			this.data.msgsIn.forEach((item) => { 
				if(i != index){
					if(item.x > 10){this.toZero(i);}
				}
				i++;
			});
		},
		thMove : function (e){
      e = e.detail;
      var index = e[1][0];
      var item = this.data.msgsIn[index];
      item.x -= e[0][0][0] * this.data.damping;
			if(item.x > this.data.btnWidth){item.x = this.data.btnWidth;}
			if(item.x < 0){item.x = 0;}
			this.data.msgsIn.splice(index, 1, item);
      this.data.damping *= 1.2;
      this.setData({msgsIn:this.data.msgsIn, damping:this.data.damping});
		},
		thEnd : function(e){
      e = e.detail;
      var index = e[1][0];
      if(e[0][1] < 150){
				if(this.data.msgsIn[index].x >= 5){
					this.toZero(index);
					return;
				}
        if(Math.abs(e[0][0][0]) < 30){this.triggerEvent('itemTap',index);}
				return ;
			}
			var item = this.data.msgsIn[index];
			if(item.x < this.data.btnWidth / 3){item.x = 0;}else{item.x = this.data.btnWidth;}
      this.data.msgsIn.splice(index, 1, item);
      this.setData({msgsIn : this.data.msgsIn});
		},
		toZero:function(index){
			if(this.data.msgsIn[index].x < 0 ){
				this.data.msgsIn[index].x = 0;
        this.data.msgsIn.splice(index, 1, this.data.msgs[index]);
        this.setData({msgsIn : this.data.msgsIn});
				return;
			}
			this.data.msgsIn[index].x -= 10;
      this.data.msgsIn.splice(index, 1, this.data.msgsIn[index]);
      this.setData({msgsIn : this.data.msgsIn});
			setTimeout(()=>{this.toZero(index);},10);
		},
		btnTap : function (e) {
      var datas = e.currentTarget.dataset.indexs;
      this.triggerEvent('btnTap', datas);
		}
	}
})
function defineReactive(data, key, val, fn) {
  Object.defineProperty(data, key, {
    configurable: true,
    enumerable: true,
    get: function () {return val;},
    set: function (newVal) {
      if (newVal === val) return
      fn && fn(newVal)
      val = newVal
    }
  })
}
function watch(ctx, obj) {
  Object.keys(obj).forEach(key => {
    defineReactive(ctx.data, key, ctx.data[key], function (value) {obj[key].call(ctx, value);});
  });
}